package com.javaex.book.dao.impl;

import java.util.List;

import com.javaex.book.dao.OrderDao;
import com.javaex.book.pojo.Order;

public class OrderDaoImpl extends BaseDao implements OrderDao {

	@Override
	public Integer saveOrder(Order order) {
		String sql = "insert into orders(id, userId, totalPrice) values(?, ?, ?)";
		return execute(sql, order);
	}
	
	@Override
	public Integer countOrders(Integer userId) {
		if (userId == null) {
			String sql = "select count(*) from orders";
			return count(sql, null);
		}
		String sql = "select count(*) from orders where userId = ?";
		return count(sql, new Object[] { userId });
	}

	@Override
	public List<Order> queryOrdersByUserId(Integer userId, Integer start, Integer pageSize) {
		if (userId == null) {
			return null;
		}
		String sql = "select id, createTime, status, userId, totalPrice from orders where userId = ? order by createTime desc limit ?, ?";
		return findMany(sql, Order.class, new Object[] { userId, start, pageSize });
	}
	
	@Override
	public Order queryOrderById(String orderId) {
		String sql = "select id, createTime, status, userId, totalPrice from orders where id = ?";
		return findOne(sql, Order.class, new Object[] { orderId });
	}
	
	@Override
	public Integer changeOrderStatus(String orderId, Integer status) {
		String sql = "update orders set status = ? where id = ?";
		return execute(sql, new Object[] { status, orderId });
	}
	
	@Override
	public Integer deleteOrder(String orderId) {
		String sql = "delete from orders where id = ?";
		return execute(sql, new Object[] { orderId });
	}
	
	@Override
	public List<Order> queryOrders(Integer start, Integer pageSize) {
		String sql = "select id, createTime, status, userId, totalPrice from orders order by createTime desc limit ?, ?";
		return findMany(sql, Order.class, new Object[] { start, pageSize });
	}
}
